var Promise  = require('bluebird');
var BidInfo    = require('../models/bidInfo');
var BidCoupon  = require('../models/bidCoupon');
var using = Promise.using;

function getAggregatedBidDetail(id){
  return BidInfo.getAggregatedBidDetail(id, "req.postbody.auth" || '')
    .then(function(result){
      if(typeof result !== 'object') result = JSON.parse(result)
      if(result && result.body){
        result = result.body; 
        if(typeof result !== 'object') result = JSON.parse(result)
        return result; 
      }else{
        return {}
      }
    }
  )
}

function queryPerfectHkjh(id){
  return BidInfo.queryPerfectHkjh(id, "req.postbody.auth" || '')
    .then(function(result){
      if(typeof result !== 'object') result = JSON.parse(result)
      if(result && result.body){
        result = result.body;  
        if(typeof result !== 'object') result = JSON.parse(result)
        return result; 
      }else{
        return {}
      }
    }
  ) 
}

function getAvailableCouponList(id){
  return BidCoupon.getAvailableCouponList(id, "req.postbody.auth" || '', req.ip)
    .then(function(result){
      if(result && result.body){
        result = result.body;  
        return result; 
      }else{
        return {}
      }
    })
    .catch(function(err){
      // console.log(err)
      return {}
    })
}

function queryUserStatusForH5(){
  return BidCoupon.queryUserStatusForH5("req.postbody.auth" || '', '127.0.0.1')
    .then(function(result){
      if(result && result.body){
        result = result.body;  
        return result; 
      }else{
        return {}
      }
    }
  )
}

function getConnection(res) {
  return new Promise(function(resolve) {
    //不使用 new Promise时，这里会显式的抛出一个异常
    var time = 0;//Math.random() * 100;
    // console.log('traceId:' + res.req.id + ' setTimeout:time-->' + time)
    setTimeout(function () { 
      return resolve({
        responseMessage: 'dddd',
        bidDetail:{
          bidId: '1111',
          bidTitle: '2222'
        }
      })
    }, time); 
  });
}

module.exports ={
  detail : function(id, cb){
    return using(
      getAggregatedBidDetail(id),
      queryPerfectHkjh(id),
      // getConnection(),
      cb
    )
  }
}